<template>
  <section class='f-upload-data'>
    <van-form ref="formRef" @submit="onSubmit" input-align="right" error-message-align="right">

      <van-cell-group>
        <van-field v-model="form.shopName" name="shopName" label="供应商" placeholder="请选择要上传的供应商"
          :rules="[{ required: true, message: '请选择要上传的供应商' }]" right-icon="arrow" readonly @click="openPicker('选择供应商')" />
        <van-field v-model="form.goodsName" name="goodsName" label="供应商商品" placeholder="请选择一个供应商商品"
          :rules="[{ required: true, message: '请选择一个供应商商品' }]" right-icon="arrow" readonly @click="openPicker('选择供应商商品')" />
      </van-cell-group>

      <van-cell-group class="f-mt-15">
        <van-field v-if="goodsForm.withPhone" v-model="form.phone" name="phone" label="激活号码" placeholder="请输入激活号码" type="tel"
          maxlength="11" :rules="[{ required: true, message: '请填写激活号码'}]" />

        <van-field v-if="goodsForm.withIdcardName" v-model="form.idcardName" name="idcardName" label="机主姓名" placeholder="请输入机主姓名"
          :rules="[{ required: true, message: '请填写机主姓名' }]" />

        <van-field v-if="goodsForm.withExtraTxt1" v-model="form.withExtraTxt1" name="withExtraTxt1"
          :label="goodsForm.extraTxt1Name" :placeholder="'请输入' + goodsForm.extraTxt1Name"
          :rules="[{ required: true, message: '请填写补充标签一' }]" />

        <van-field v-if="goodsForm.withExtraTxt2" v-model="form.withExtraTxt2" name="withExtraTxt2"
          :label="goodsForm.extraTxt2Name" :placeholder="'请输入' + goodsForm.extraTxt2Name"
          :rules="[{ required: true, message: '请填写补充标签一' }]" />

        <van-field v-if="goodsForm.withExtraTxt3" v-model="form.withExtraTxt3" name="withExtraTxt3"
          :label="goodsForm.extraTxt3Name" :placeholder="'请输入' + goodsForm.extraTxt3Name"
          :rules="[{ required: true, message: '请填写补充标签一' }]" />
      </van-cell-group>

      <p class="f-mt-15 f-title">上传开卡照片</p>
      <van-cell-group class="f-flex-row" style="flex-wrap:wrap">
        <van-field v-if="goodsForm.withIdcardFront" name="withImg1" :rules="[{ required: true, message: '请上传身份证人像面' }]"
          error-message-align="center" style="width:50%;padding:10px">
          <template #input>
            <section>
              <van-uploader v-model="imgForm.withImg1" :after-read="afterRead1" :max-count="1" :preview-size="['167px', '104px']"
                @click-upload="imgName = 'withImg1'">
                <img class="f-img1" src="@/assets/imgs/jhh_datum_pic01.png" alt="">
              </van-uploader>
              <p class="f-center" style="font-size: 12px;color: #424242;">身份证人像面</p>
            </section>
          </template>
        </van-field>
        <van-field v-if="goodsForm.withIdcardBack" name="withImg2" :rules="[{ required: true, message: '请上传身份证国徽面' }]"
          error-message-align="center" style="width:50%;padding:10px">
          <template #input>
            <section>
              <van-uploader v-model="imgForm.withImg2" :after-read="afterRead2" :max-count="1" :preview-size="['167px', '104px']"
                @click-upload="imgName = 'withImg2'">
                <img class="f-img1" src="@/assets/imgs/jhh_datum_pic02.png" alt="">
              </van-uploader>
              <p class="f-center" style="font-size: 12px;color: #424242;">身份证国徽面</p>
            </section>
          </template>
        </van-field>
        <van-field v-if="goodsForm.withIdcardOwner" name="withImg3" :rules="[{ required: true, message: '请上传手持身份证照' }]"
          error-message-align="center" style="width:50%;padding:10px">
          <template #input>
            <section>
              <van-uploader v-model="imgForm.withImg3" :after-read="afterRead3" :max-count="1" :preview-size="['167px', '104px']"
                @click-upload="imgName = 'withImg3'">
                <img class="f-img1" src="@/assets/imgs/jhh_datum_pic03.png" alt="">
              </van-uploader>
              <p class="f-center" style="font-size: 12px;color: #424242;">手持身份证照</p>
            </section>
          </template>
        </van-field>
        <van-field v-if="goodsForm.withOwnerAntiFraud" name="withImg4" :rules="[{ required: true, message: '请上传手持反诈说明' }]"
          error-message-align="center" style="width:50%;padding:10px">
          <template #input>
            <section>
              <van-uploader v-model="imgForm.withImg4" :after-read="afterRead4" :max-count="1" :preview-size="['167px', '104px']"
                @click-upload="imgName = 'withImg4'">
                <img class="f-img1" src="@/assets/imgs/jhh_datum_pic04.png" alt="">
              </van-uploader>
              <p class="f-center" style="font-size: 12px;color: #424242;">手持反诈说明</p>
            </section>
          </template>
        </van-field>
        <van-field v-if="goodsForm.withExtraImg1" name="withExtraImg1" :rules="[{ required: true, message: '请上传扩展图片' }]"
          error-message-align="center" style="width:50%;padding:10px">
          <template #input>
            <section>
              <van-uploader v-model="imgForm.withExtraImg1" :after-read="afterRead5" :max-count="1"
                :preview-size="['167px', '104px']" @click-upload="imgName = 'withExtraImg1'">
                <img class="f-img1" src="@/assets/imgs/jhh_datum_pic05.png" alt="">
              </van-uploader>
              <p class="f-center" style="font-size: 12px;color: #424242;">{{goodsForm.extraImg1Name}}</p>
            </section>
          </template>
        </van-field>
        <van-field v-if="goodsForm.withExtraImg2" name="withExtraImg2" :rules="[{ required: true, message: '请上传扩展图片' }]"
          error-message-align="center" style="width:50%;padding:10px">
          <template #input>
            <section>
              <van-uploader v-model="imgForm.withExtraImg2" :after-read="afterRead6" :max-count="1"
                :preview-size="['167px', '104px']" @click-upload="imgName = 'withExtraImg2'">
                <img class="f-img1" src="@/assets/imgs/jhh_datum_pic05.png" alt="">
              </van-uploader>
              <p class="f-center" style="font-size: 12px;color: #424242;">{{goodsForm.extraImg2Name}}</p>
            </section>
          </template>
        </van-field>
        <van-field v-if="goodsForm.withExtraImg3" name="withExtraImg3" :rules="[{ required: true, message: '请上传扩展图片' }]"
          error-message-align="center" style="width:50%;padding:10px">
          <template #input>
            <section>
              <van-uploader v-model="imgForm.withExtraImg3" :after-read="afterRead7" :max-count="1"
                :preview-size="['167px', '104px']" @click-upload="imgName = 'withExtraImg3'">
                <img class="f-img1" src="@/assets/imgs/jhh_datum_pic05.png" alt="">
              </van-uploader>
              <p class="f-center" style="font-size: 12px;color: #424242;">{{goodsForm.extraImg3Name}}</p>
            </section>
          </template>
        </van-field>
      </van-cell-group>

      <div class="f-submit-btn">
        <van-button round block type="primary" native-type="submit">提交</van-button>
      </div>
    </van-form>

    <van-popup v-model:show="showPicker" closeable position="bottom" close-icon-position="top-left">
      <p class="f-popup-title">{{pickerTitle}}</p>
      <section v-if="pickerTitle == '选择供应商'">
        <van-picker ref="pickerRef" v-model="selectShopId" :columns="mySupplierList" :columns-field-names="customFieldName"
          :show-toolbar="false" />
        <div class="f-popup-btn">
          <van-button block type="primary" @click="handlePicker()">确定</van-button>
        </div>
      </section>

      <van-cascader v-else v-model="cascaderValue" :options="goodsList" :field-names="fieldNames" :show-header="false"
        @finish="handleCascader" />

    </van-popup>
  </section>
</template>
<script>
import { ref, reactive, toRefs, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex';
import { showToast, showSuccessToast, closeToast, showLoadingToast } from 'vant';
import api from '../api'

export default {
  setup(props, context) {
    const store = useStore()

    const router = useRouter()
    const route = useRoute();

    const formRef = ref()
    const pickerRef = ref()

    const state = reactive({
      form: {
        "createTime": "",
        "goodsName": "",
        "goodsId": "",
        "iccid": "",
        "idcardName": "",
        "idcardNum": "",
        "phone": "",
        "productId": "",
        "shopId": "",
        "withExtraImg1": "",
        "withExtraImg2": "",
        "withExtraImg3": "",
        "withExtraTxt1": "",
        "withExtraTxt2": "",
        "withExtraTxt3": "",
        "withImg1": "",
        "withImg2": "",
        "withImg3": "",
        "withImg4": ""
      },
      goodsForm: {},
      imgName: '',
      imgForm: {},

      showPicker: false,
      pickerTitle: '',
      selectShopId: [],
      mySupplierList: [],
      customFieldName: {
        text: 'shopName',
        value: 'shopId',
        children: 'children'
      },

      goodsList: [],
      cascaderValue: '',
      fieldNames: {
        text: 'goodsName',
        value: 'goodsId',
        children: 'goodsInfoList',
      }
    })

    onMounted(() => {
      store.commit("setNavBar", {
        title: '资料上传',
        show: true,
        left: true,
        leftType: 'back',
        right: false,
        rightType: 'search',
      });

      getSupplierList()
    })

    const getSupplierList = () => {
      api.mySupplierList().then(res => {
        state.mySupplierList = res.data
      })
    };

    const afterRead1 = (files) => {
      files.status = 'uploading';
      files.message = '上传中...';
      const formData = new FormData();
      formData.append("file", files.file) // 这里填入你的file文件对象

      api.uploadImgPrivate(formData).then(res => {
        files.status = 'done';
        state.form.withImg1 = res.data.ossUrl

      }).catch(err => {
        files.status = 'failed';
        files.message = '上传失败';
      })
    };

    const afterRead2 = (files) => {
      files.status = 'uploading';
      files.message = '上传中...';
      const formData = new FormData();
      formData.append("file", files.file) // 这里填入你的file文件对象

      api.uploadImgPrivate(formData).then(res => {
        files.status = 'done';
        state.form.withImg2 = res.data.ossUrl

      }).catch(err => {
        files.status = 'failed';
        files.message = '上传失败';
      })
    };

    const afterRead3 = (files) => {
      files.status = 'uploading';
      files.message = '上传中...';
      const formData = new FormData();
      formData.append("file", files.file) // 这里填入你的file文件对象

      api.uploadImgPrivate(formData).then(res => {
        files.status = 'done';
        state.form.withImg3 = res.data.ossUrl

      }).catch(err => {
        files.status = 'failed';
        files.message = '上传失败';
      })
    };

    const afterRead4 = (files) => {
      files.status = 'uploading';
      files.message = '上传中...';
      const formData = new FormData();
      formData.append("file", files.file) // 这里填入你的file文件对象

      api.uploadImgPrivate(formData).then(res => {
        files.status = 'done';
        state.form.withImg4 = res.data.ossUrl

      }).catch(err => {
        files.status = 'failed';
        files.message = '上传失败';
      })
    };

    const afterRead5 = (files) => {
      files.status = 'uploading';
      files.message = '上传中...';
      const formData = new FormData();
      formData.append("file", files.file) // 这里填入你的file文件对象

      api.uploadImgPrivate(formData).then(res => {
        files.status = 'done';
        state.form.withExtraImg1 = res.data.ossUrl

      }).catch(err => {
        files.status = 'failed';
        files.message = '上传失败';
      })
    };

    const afterRead6 = (files) => {
      files.status = 'uploading';
      files.message = '上传中...';
      const formData = new FormData();
      formData.append("file", files.file) // 这里填入你的file文件对象

      api.uploadImgPrivate(formData).then(res => {
        files.status = 'done';
        state.form.withExtraImg2 = res.data.ossUrl

      }).catch(err => {
        files.status = 'failed';
        files.message = '上传失败';
      })
    };

    const afterRead7 = (files) => {
      files.status = 'uploading';
      files.message = '上传中...';
      const formData = new FormData();
      formData.append("file", files.file) // 这里填入你的file文件对象

      api.uploadImgPrivate(formData).then(res => {
        files.status = 'done';
        state.form.withExtraImg3 = res.data.ossUrl

      }).catch(err => {
        files.status = 'failed';
        files.message = '上传失败';
      })
    };

    const openPopup = () => {
      state.showPopup = true
    }

    const onFinish = ({ selectedOptions }) => {
      state.showPopup = false;
      // fieldValue.value = selectedOptions.map((option) => option.text).join('/');
    };

    const onSubmit = (values) => {
      let json = JSON.parse(JSON.stringify(state.form))
      json.extraImg1Name = state.goodsForm.extraImg1Name
      json.extraImg2Name = state.goodsForm.extraImg2Name
      json.extraImg3Name = state.goodsForm.extraImg3Name
      json.extraTxt1Name = state.goodsForm.extraTxt1Name
      json.extraTxt2Name = state.goodsForm.extraTxt2Name
      json.extraTxt3Name = state.goodsForm.extraTxt3Name

      showLoadingToast({
        message: '提交中...',
        forbidClick: true,
        duration: 0
      });
      api.orderUpload(json).then(res => {
        showSuccessToast('资料上传成功')
        setTimeout(() => {
          closeToast()
          router.go(-1)
        }, 1000)
      }).catch(err => {
        closeToast()
      })
    };

    const openPicker = (name) => {
      if (name == '选择供应商') {
        state.pickerTitle = name
        state.showPicker = true
      } else if (name == '选择供应商商品') {
        if (!state.form.shopId) {
          showToast('请先选择供应商！')
        } else {
          let json = {
            shopId: state.form.shopId
          }
          api.goodsByOperator(json).then(res => {
            state.goodsList = setGoodsList(res.data)
            state.pickerTitle = name
            state.showPicker = true
          })

        }
      }
    }

    function setGoodsList(list = []) {
      const myArr = []
      list && list.map(item => {
        if (!item.goodsInfoList || (item.goodsInfoList.length == 0)) return
        myArr.push(...item.goodsInfoList)
      })

      return myArr
    }

    const handlePicker = (e) => {
      let data = pickerRef.value.confirm().selectedOptions[0]
      state.form.shopName = data.shopName
      state.form.shopId = data.shopId
      state.showPicker = false
    }

    const handleCascader = (e) => {
      state.goodsForm = e.selectedOptions[0]
      state.form.goodsName = state.goodsForm.goodsName
      state.form.goodsId = state.goodsForm.goodsId
      state.form.productId = state.goodsForm.productId
      state.showPicker = false
    }

    return {
      ...toRefs(state),
      formRef,
      pickerRef,
      afterRead1,
      afterRead2,
      afterRead3,
      afterRead4,
      afterRead5,
      afterRead6,
      afterRead7,
      onSubmit,
      onFinish,
      openPopup,
      openPicker,
      handlePicker,
      handleCascader,
    }
  }
}
</script>
<style lang='scss' scoped>
.f-upload-data {
  .f-submit-btn {
    margin: 20px 0;
    padding: 0 62px;
  }
  .f-img1 {
    width: 167px;
    height: 104px;
  }
  .f-title {
    padding: 15px;
    font-size: 14px;
    color: #424242;
    background: #fff;
  }
}
</style>